// Base64 URL 编码函数
function base64UrlEncode(data: string) {
  return btoa(data)
    .replace(/=+$/, '')  // 去掉填充符号
    .replace(/\+/g, '-') // '+' -> '-'
    .replace(/\//g, '_'); // '/' -> '_'
}

// 生成签名并加密 JWT
async function createJWT(header: object, payload: object, secret: string) {
  // Step 1: Base64 编码 header 和 payload
  const encodedHeader = base64UrlEncode(JSON.stringify(header));
  const encodedPayload = base64UrlEncode(JSON.stringify(payload));

  // Step 2: 生成签名
  const dataToSign = `${encodedHeader}.${encodedPayload}`;

  // 将 secret 转换为 CryptoKey
  const encoder = new TextEncoder();
  const secretKey = await crypto.subtle.importKey(
    "raw",                           // 密钥类型
    encoder.encode(secret),          // 使用 secret 编码为字节数组
    { name: "HMAC", hash: { name: "SHA-256" } }, // 使用 HMAC 和 SHA-256
    false,                            // 不允许导出密钥
    ["sign"]                          // 指定签名操作
  );

  // 使用 HMAC 签名
  const signatureBuffer = await crypto.subtle.sign(
    "HMAC",
    secretKey,
    encoder.encode(dataToSign)      // 数据进行签名
  );

  // 将签名结果转换为 Base64 URL 编码
  const signatureArray = new Uint8Array(signatureBuffer);
  const signature = base64UrlEncode(String.fromCharCode(...signatureArray));

  // 返回完整的 JWT
  return `${dataToSign}.${signature}`;
}

// 验证 JWT
async function verifyJWT(token: string, secret: string) {
  const [encodedHeader, encodedPayload, signature] = token.split('.');
  const dataToSign = `${encodedHeader}.${encodedPayload}`;
  const encoder = new TextEncoder();
  const secretKey = await crypto.subtle.importKey(
    "raw",                           // 密钥类型
    encoder.encode(secret),          // 使用 secret 编码为字节数组
    { name: "HMAC", hash: { name: "SHA-256" } }, // 使用 HMAC 和 SHA-256
    false,                            // 不允许导出密钥
    ["sign"]                          // 指定签名操作
  );

  const signatureBuffer = await crypto.subtle.sign(
    "HMAC",
    secretKey,
    encoder.encode(dataToSign)      // 数据进行签名
  );

  const signatureArray = new Uint8Array(signatureBuffer);
  const expectedSignature = base64UrlEncode(String.fromCharCode(...signatureArray));

  return expectedSignature === signature;
}

const secret = "abcdfghjkqwertyui";
export async function generateToken(userId: number) {
  const header = {
    alg: "HS256",
    typ: "JWT"
  };

  const payload = {
    userId: userId,
    iat: Math.floor(Date.now() / 1000)
  };

  return await createJWT(header, payload, secret);
}
// 验证 JWT
export async function verifyToken(token) {
  const isValid = await verifyJWT(token, secret);
  console.log("Is token valid:", isValid);
  return isValid;

}
